<?php

namespace shisou\tpgii\handler;

class Sql
{
    private $tables;

    public function __construct(array $tables)
    {
        $this->tables = $tables;
    }

    public function run()
    {
        $sql = '';

        // loop tables
        foreach ($this->tables as $tb) {
            $singleTableSql = '';

            $singleTableSql .= $this->globalSql1($tb);

            // loop cols
            foreach ($tb['cols'] as $col) {
                $singleTableSql .= $this->colSql($col);
            }

            $singleTableSql .= $this->globalSql2($tb['tableNameCn']);

            $sql .= $singleTableSql;
        }

        file_put_contents(root_path() . '/db.sql', $sql);
    }

    private function globalSql1($table)
    {
        $sql = '';

        // COMMENT
        $sql .= "# {$table['tableNameCn']}" . "\n";

        // DROP TABLE
        $sql .= "DROP TABLE IF EXISTS `{$table['tableName']}`;" . "\n";

        // CREATE TABLE START
        $sql .= "CREATE TABLE `{$table['tableName']}` (" . "\n";
        $sql .= "\t" . "`id`         INT(10) NOT NULL AUTO_INCREMENT," . "\n";
        $sql .= "\t" . "`created_at` DATETIME NOT NULL DEFAULT NOW()," . "\n";
        $sql .= "\t" . "`updated_at` DATETIME NOT NULL," . "\n";
        $sql .= "\t" . "`status`     TINYINT(1) NOT NULL DEFAULT 1," . "\n";
        $sql .= "\n";

        return $sql;
    }

    private function colSql($col)
    {
        $sql = '';

        // tab
        $sql .= "\t";

        // column name
        $sql .= str_pad("`{$col['col']}`", 20);

        // type and length
        if ($col['len']) {
            $sql .= ' ' . str_pad("{$col['type']}({$col['len']})", 13);
        } else {
            // DATETIME etc.
            $sql .= ' ' . str_pad("{$col['type']}", 13);
        }

        // NOT NULL
        // $sql .= " NOT NULL";

        // DEFAULT
        // if there is INT, regardless INT/TINYINT/MEDIUMINT/BIGINT,
        // then it should be default 0
        if (strpos($col['type'], 'INT') !== false) {
            $sql .= " DEFAULT 0           ";
        } elseif ($col['type'] == 'VARCHAR') {
            $sql .= " DEFAULT ''          ";
        } elseif ($col['type'] == 'TEXT') {
            $sql .= "                     ";
        } elseif ($col['type'] == 'DATETIME') {
            $sql .= "                     ";
        } elseif ($col['type'] == 'DECIMAL') {
            $sql .= " DEFAULT 0           ";
        }

        // COMMENT
        $sql .= " COMMENT '{$col['colCn']}'";

        $sql .= "," . "\n";

        return $sql;
    }

    private function globalSql2($tableNameCn)
    {
        $sql = "\n";

        // PRIMARY KEY
        $sql .= "\t" . "PRIMARY KEY(`id`)" . "\n";

        // ENGINE=InnoDB MyISAM
        $sql .= ") ENGINE=InnoDb CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci COMMENT '{$tableNameCn}';" . "\n\n\n";

        return $sql;
    }
}
